package com.haixiaoke.common;

import com.haixiaoke.saas.common.config.SaasConfig;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.oss.AliOssServiceImpl;
import com.haixiaoke.saas.common.utils.file.FileUtils;
import com.haixiaoke.saas.system.framework.config.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 通用请求处理
 *
 * @author haixiaoke
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    private static final String FILE_DELIMETER = ",";
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private AliOssServiceImpl aliOssService;

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = SaasConfig.getUploadPath();

            // 上传并返回新文件名称
            // String fileName = FileUploadUtils.upload(filePath, file);
            // String url = serverConfig.getUrl() + fileName;

            // 上传并返回新文件名称
            String url = aliOssService.upload("saas-v5", file.getOriginalFilename(), file);
            String fileName = file.getOriginalFilename();
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


}
